<template>
  <div class="order-detail-container">
    <Header />

    <div class="main-content">
      <div class="order-detail-wrapper">
        <div class="page-header">
          <el-page-header @back="goBack" content="订单详情"></el-page-header>
        </div>

        <div v-loading="loading">
          <!-- 订单不存在 -->
          <div v-if="!order && !loading" class="empty-state">
            <el-empty description="订单不存在或已被删除" :image-size="200">
              <el-button type="primary" @click="goToOrders"
                >返回订单列表</el-button
              >
            </el-empty>
          </div>

          <!-- 订单详情内容 -->
          <div v-if="order" class="order-content">
            <!-- 订单状态卡片 -->
            <el-card class="status-card">
              <div class="status-header">
                <div class="status-title">
                  <i class="el-icon-document"></i>
                  <span>订单状态</span>
                </div>
                <div class="status-value" :class="'status-' + order.status">
                  {{ getStatusText(order.status) }}
                </div>
              </div>

              <el-steps
                :active="getStatusStep(order.status)"
                finish-status="success"
                simple
              >
                <el-step title="待付款"></el-step>
                <el-step title="待接单"></el-step>
                <el-step title="备餐中"></el-step>
                <el-step title="配送中"></el-step>
                <el-step title="已完成"></el-step>
              </el-steps>

              <div class="order-time-info">
                <div class="time-item">
                  <span class="label">下单时间：</span>
                  <span class="value">{{ formatDate(order.createTime) }}</span>
                </div>
                <div class="time-item" v-if="order.paymentTime">
                  <span class="label">支付时间：</span>
                  <span class="value">{{ formatDate(order.paymentTime) }}</span>
                </div>
                <div class="time-item" v-if="order.deliveryTime">
                  <span class="label">配送时间：</span>
                  <span class="value">{{
                    formatDate(order.deliveryTime)
                  }}</span>
                </div>
                <div class="time-item" v-if="order.completeTime">
                  <span class="label">完成时间：</span>
                  <span class="value">{{
                    formatDate(order.completeTime)
                  }}</span>
                </div>
                <div class="time-item" v-if="order.cancelTime">
                  <span class="label">取消时间：</span>
                  <span class="value">{{ formatDate(order.cancelTime) }}</span>
                </div>
                <div class="time-item" v-if="order.cancelReason">
                  <span class="label">取消原因：</span>
                  <span class="value">{{ order.cancelReason }}</span>
                </div>
              </div>

              <!-- 订单操作按钮 -->
              <div class="order-actions">
                <!-- 待付款状态 -->
                <template v-if="order.status === 0">
                  <el-button type="primary" @click="payOrder">去支付</el-button>
                  <el-button @click="cancelOrder">取消订单</el-button>
                </template>

                <!-- 配送中状态 -->
                <template v-if="order.status === 3">
                  <el-button type="primary" @click="completeOrder"
                    >确认收货</el-button
                  >
                </template>

                <!-- 已完成状态 -->
                <template v-if="order.status === 4 && !order.hasReviewed">
                  <el-button type="primary" @click="reviewOrder"
                    >评价订单</el-button
                  >
                </template>

                <!-- 已完成或已取消状态可以删除 -->
                <template v-if="order.status === 4 || order.status === 5">
                  <el-button type="danger" @click="deleteOrder"
                    >删除订单</el-button
                  >
                </template>
              </div>
            </el-card>

            <!-- 订单基本信息 -->
            <el-card class="order-info-card">
              <div slot="header" class="card-header">
                <span>订单信息</span>
              </div>

              <div class="info-item">
                <span class="label">订单编号：</span>
                <span class="value">{{ order.orderNo }}</span>
              </div>

              <div class="info-item">
                <span class="label">商家名称：</span>
                <span class="value">{{
                  order.merchantName || "未知商家"
                }}</span>
              </div>

              <div class="info-item">
                <span class="label">支付方式：</span>
                <span class="value">{{
                  getPaymentMethodText(order.paymentMethod)
                }}</span>
              </div>

              <div class="info-item" v-if="order.remark">
                <span class="label">订单备注：</span>
                <span class="value">{{ order.remark }}</span>
              </div>
            </el-card>

            <!-- 配送信息 -->
            <el-card class="delivery-card">
              <div slot="header" class="card-header">
                <span>配送信息</span>
              </div>

              <div class="info-item">
                <span class="label">收货人：</span>
                <span class="value">{{ order.receiverName }}</span>
              </div>

              <div class="info-item">
                <span class="label">联系电话：</span>
                <span class="value">{{ order.receiverPhone }}</span>
              </div>

              <div class="info-item">
                <span class="label">配送地址：</span>
                <span class="value">{{ order.deliveryAddress }}</span>
              </div>
            </el-card>

            <!-- 商品信息 -->
            <el-card class="foods-card">
              <div slot="header" class="card-header">
                <span>商品信息</span>
              </div>

              <el-table
                :data="order.orderDetails || []"
                style="width: 100%"
                :show-header="true"
              >
                <el-table-column label="商品" min-width="300">
                  <template slot-scope="scope">
                    <div class="food-item">
                      <div class="food-image">
                        <img
                          :src="scope.row.foodImage"
                          v-if="scope.row.foodImage"
                        />
                        <div class="placeholder" v-else></div>
                      </div>
                      <div class="food-name">{{ scope.row.foodName }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="单价" width="100">
                  <template slot-scope="scope">
                    <span class="price">¥{{ scope.row.price }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="quantity"
                  label="数量"
                  width="100"
                ></el-table-column>
                <el-table-column prop="subtotal" label="小计" width="120">
                  <template slot-scope="scope">
                    <span class="price">¥{{ scope.row.subtotal }}</span>
                  </template>
                </el-table-column>
              </el-table>

              <div class="order-summary">
                <div class="summary-item">
                  <span class="label">商品总额：</span>
                  <span class="value">¥{{ order.totalPrice }}</span>
                </div>
                <div class="summary-item">
                  <span class="label">配送费：</span>
                  <span class="value">¥0.00</span>
                </div>
                <div class="summary-item total">
                  <span class="label">实付款：</span>
                  <span class="value price">¥{{ order.totalPrice }}</span>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>

    <!-- 评价对话框 -->
    <el-dialog
      title="订单评价"
      :visible.sync="reviewDialogVisible"
      width="500px"
    >
      <el-form :model="reviewForm" ref="reviewForm" :rules="reviewRules">
        <el-form-item label="评分" prop="rating">
          <el-rate
            v-model="reviewForm.rating"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          ></el-rate>
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input
            type="textarea"
            v-model="reviewForm.content"
            :rows="4"
            placeholder="请输入您的评价内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reviewDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReview" :loading="submitting"
          >提 交</el-button
        >
      </span>
    </el-dialog>

    <Footer />
  </div>
</template>

<script>
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import { mapGetters } from "vuex";
import {
  getOrderById,
  cancelOrder,
  completeOrder,
  deleteOrder,
  payOrder
} from "@/api/order";
import { addReview } from "@/api/review";

export default {
  name: "OrderDetail",
  components: {
    Header,
    Footer,
  },
  props: {
    id: {
      type: [Number, String],
      required: true,
    },
  },
  data() {
    return {
      // 订单详情
      order: null,
      // 加载状态
      loading: false,

      // 评价对话框
      reviewDialogVisible: false,
      reviewForm: {
        orderId: null,
        merchantId: null,
        rating: 5,
        content: "",
      },
      reviewRules: {
        rating: [{ required: true, message: "请给出评分", trigger: "change" }],
        content: [
          { required: true, message: "请输入评价内容", trigger: "blur" },
          {
            min: 5,
            max: 200,
            message: "评价内容长度在5到200个字符之间",
            trigger: "blur",
          },
        ],
      },
      submitting: false,
    };
  },
  computed: {
    ...mapGetters(["currentUser"]),
    // 获取URL中的action参数
    action() {
      return this.$route.query.action;
    },
  },
  created() {
    this.fetchOrderDetail();
  },
  mounted() {
    // 检查是否需要自动执行操作
    this.$nextTick(() => {
      if (this.action === "pay" && this.order && this.order.status === 0) {
        this.payOrder();
      }
    });
  },
  methods: {
    // 获取订单详情
    fetchOrderDetail() {
      this.loading = true;

      getOrderById(this.id)
        .then((response) => {
          if (response.code === 200) {
            this.order = response.data;

            // 检查是否需要自动执行操作
            if (this.action === "pay" && this.order.status === 0) {
              this.payOrder();
            }
          } else {
            this.$message.error(response.message || "获取订单详情失败");
          }
        })
        .catch((error) => {
          console.error("获取订单详情失败", error);
          this.$message.error("获取订单详情失败，请稍后再试");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 返回上一页
    goBack() {
      this.$router.back();
    },

    // 返回订单列表
    goToOrders() {
      this.$router.push("/orders");
    },

    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        0: "待付款",
        1: "待接单",
        2: "备餐中",
        3: "配送中",
        4: "已完成",
        5: "已取消",
      };
      return statusMap[status] || "未知状态";
    },

    // 获取订单步骤
    getStatusStep(status) {
      if (status === 5) {
        // 已取消
        return 0;
      } else if (status === 4) {
        // 已完成
        return 4;
      } else {
        return status;
      }
    },

    // 获取支付方式文本
    getPaymentMethodText(method) {
      const methodMap = {
        1: "微信支付",
        2: "支付宝",
        3: "校园卡",
      };
      return methodMap[method] || "未知方式";
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "未知";
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(date.getDate()).padStart(2, "0")} ${String(
        date.getHours()
      ).padStart(2, "0")}:${String(date.getMinutes()).padStart(
        2,
        "0"
      )}:${String(date.getSeconds()).padStart(2, "0")}`;
    },

    // 支付订单
    payOrder() {
      // 调用支付API
      this.$confirm("确认支付此订单？", "提示", {
        confirmButtonText: "确认支付",
        cancelButtonText: "取消",
        type: "info",
      })
        .then(() => {
          // 调用支付API
          console.log(this.order);
          
          const paymentMethod = this.order.paymentMethod || 1; // 默认使用订单上的支付方式或默认为微信支付
          payOrder(this.order.id, paymentMethod)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("支付成功，订单状态已更新");
                // 重新获取订单
                this.fetchOrderDetail();
              } else {
                this.$message.error(response.message || "支付失败");
              }
            })
            .catch((error) => {
              console.error("支付失败", error);
              this.$message.error("支付失败，请稍后再试");
            });
        })
        .catch(() => {});
    },

    // 取消订单
    cancelOrder() {
      this.$confirm("确定要取消该订单吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const reason = "用户主动取消";
          cancelOrder(this.order.id, reason, this.currentUser.id)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("订单已取消");
                // 重新获取订单
                this.fetchOrderDetail();
              } else {
                this.$message.error(response.message || "取消订单失败");
              }
            })
            .catch((error) => {
              console.error("取消订单失败", error);
              this.$message.error("取消订单失败，请稍后再试");
            });
        })
        .catch(() => {});
    },

    // 确认收货
    completeOrder() {
      this.$confirm("确认已收到商品吗?", "提示", {
        confirmButtonText: "确认收货",
        cancelButtonText: "取消",
        type: "info",
      })
        .then(() => {
          completeOrder(this.order.id, this.currentUser.id)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("确认收货成功");
                // 重新获取订单
                this.fetchOrderDetail();
              } else {
                this.$message.error(response.message || "确认收货失败");
              }
            })
            .catch((error) => {
              console.error("确认收货失败", error);
              this.$message.error("确认收货失败，请稍后再试");
            });
        })
        .catch(() => {});
    },

    // 删除订单
    deleteOrder() {
      this.$confirm("确定要删除该订单吗? 删除后将无法恢复", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteOrder(this.order.id)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("订单已删除");
                // 跳转到订单列表
                this.$router.push("/orders");
              } else {
                this.$message.error(response.message || "删除订单失败");
              }
            })
            .catch((error) => {
              console.error("删除订单失败", error);
              this.$message.error("删除订单失败，请稍后再试");
            });
        })
        .catch(() => {});
    },

    // 评价订单
    reviewOrder() {
      this.reviewForm = {
        orderId: this.order.id,
        merchantId: this.order.merchantId,
        rating: 5,
        content: "",
      };
      this.reviewDialogVisible = true;
    },

    // 提交评价
    submitReview() {
      this.$refs.reviewForm.validate((valid) => {
        if (valid) {
          this.submitting = true;

          // 添加用户ID
          const reviewData = {
            ...this.reviewForm,
            userId: this.currentUser.id,
          };

          addReview(reviewData)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("评价提交成功");
                this.reviewDialogVisible = false;
                // 重新获取订单
                this.fetchOrderDetail();
              } else {
                this.$message.error(response.message || "评价提交失败");
              }
            })
            .catch((error) => {
              console.error("评价提交失败", error);
              this.$message.error("评价提交失败，请稍后再试");
            })
            .finally(() => {
              this.submitting = false;
            });
        }
      });
    },
  },
};
</script>

<style scoped>
.order-detail-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.main-content {
  flex: 1;
  padding: 30px 0;
}

.order-detail-wrapper {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  margin-bottom: 20px;
}

.empty-state {
  padding: 50px 0;
  text-align: center;
}

.status-card,
.order-info-card,
.delivery-card,
.foods-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.status-title {
  font-size: 16px;
  display: flex;
  align-items: center;
}

.status-title i {
  margin-right: 8px;
  font-size: 18px;
}

.status-value {
  font-size: 18px;
  font-weight: bold;
}

.status-0 {
  color: #e6a23c;
}
.status-1 {
  color: #409eff;
}
.status-2 {
  color: #409eff;
}
.status-3 {
  color: #409eff;
}
.status-4 {
  color: #67c23a;
}
.status-5 {
  color: #909399;
}

.order-time-info {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #eee;
}

.time-item {
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.time-item:last-child {
  margin-bottom: 0;
}

.time-item .label {
  display: inline-block;
  width: 100px;
  color: #909399;
}

.order-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
}

.info-item {
  margin-bottom: 12px;
  font-size: 14px;
  line-height: 1.5;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .label {
  display: inline-block;
  width: 100px;
  color: #909399;
}

.food-item {
  display: flex;
  align-items: center;
}

.food-image {
  width: 50px;
  height: 50px;
  margin-right: 10px;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f0f0f0;
}

.food-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.food-image .placeholder {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
}

.price {
  color: #ff6b00;
  font-weight: bold;
}

.order-summary {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #eee;
  text-align: right;
}

.summary-item {
  margin-bottom: 10px;
  font-size: 14px;
}

.summary-item.total {
  font-size: 16px;
  font-weight: bold;
}

.summary-item .value {
  margin-left: 10px;
  display: inline-block;
  min-width: 80px;
}
</style> 